package cn.com.taiji.pos.controller;


import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.pos.common.util.HttpUtil;
import cn.com.taiji.pos.entity.CardAccount;
import cn.com.taiji.pos.entity.CardInfo;
import cn.com.taiji.pos.entity.SystemAclUser;
import cn.com.taiji.pos.service.ICardAccountService;
import cn.com.taiji.pos.service.ICardCustomerTypeService;
import cn.com.taiji.pos.service.ICardInfoService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.github.dreamyoung.mprelation.AutoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/card")
public class CardController {
    @Value("${CARD_ACCOUNT_TYPE_CHUZHI}")
    private String CARD_ACCOUNT_TYPE_CHUZHI;
    @Value("${MSM_PUB_OR_URL}")
    private String MSM_PUB_OR_URL;

    @Autowired
    private ICardInfoService cardInfoService;
    @Autowired
    private ICardAccountService cardAccountService;
    @Autowired
    private ICardCustomerTypeService cardCustomerTypeService;
    @Autowired
    private AutoMapper autoMapper;


    /**
     * 关联餐卡
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "linkCard", method = RequestMethod.POST)
    public String lock(Model model, HttpServletRequest request, HttpServletResponse response) {
        String cardCode = request.getParameter("cardCode");
        String cardId = request.getParameter("cardId");
        CardInfo cardInfo = cardInfoService.findByCardCode(cardCode);
        if (cardInfo != null) {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "卡片串号已被占用");
        }
        if (cardInfoService.linkCard(cardCode, cardId)) {
            model.addAttribute("result", "success");
            model.addAttribute("message", "卡片关联成功");
        } else {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "卡片关联失败");
        }
        return JSONObject.toJSONString(model);
    }

    /**
     * 获取餐卡对应顾客信息
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "getCardCustomer", method = RequestMethod.POST)
    public String getCardCustomer(Model model, HttpServletRequest request, HttpServletResponse response) {

        String cardCode = request.getParameter("cardCode");
        if (!StringUtils.hasText(cardCode)) {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "请输入卡号");
            return JSONObject.toJSONString(model);
        }
        CardInfo cardInfo = cardInfoService.query()
                .eq("CARD_CODE", cardCode)
                .eq("STATUS", 0).one();

        if (cardInfo == null) {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "该卡片尚未关联账户");
            return JSONObject.toJSONString(model);
        }
        //查询账户
        CardAccount cardAccount = cardAccountService.query().eq("CUSTOMER_ID", cardInfo.getCustomerId())
                .eq("STATUS", 0).list().get(0);
//                .eq("ACCOUNT_TYPE_ID", CARD_ACCOUNT_TYPE_CHUZHI);
        model.addAttribute("result", "success");
//        model.addAttribute("cardInfo",cardInfo);
        if (cardAccount == null) {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "该卡片未开通账户");
            return JSONObject.toJSONString(model);
        }
        model.addAttribute("cardAccount", autoMapper.mapperEntity(cardAccount));
        model.addAttribute("cardCustomerType", cardCustomerTypeService.getById(cardAccount.getCustomer().getCustomerTypeId()).getName());
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("id", "accountType", "result", "cardAccount", "accountNo", "amount", "customer", "cardCustomerType", "name");
        return JSONObject.toJSONString(model, filter, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 查询顾客账户类型
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "getCardAccountTypeList", method = RequestMethod.POST)
    public String getCardAccountTypeList(Model model, HttpServletRequest request, HttpServletResponse response) {
        String cardCode = request.getParameter("cardCode");
        if (!StringUtils.hasText(cardCode)) {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "请输入卡号");
            return JSONObject.toJSONString(model);
        }
        CardInfo cardInfo = cardInfoService.query()
                .eq("CARD_CODE", cardCode)
                .eq("STATUS", 0).one();
        if (cardInfo == null) {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "该卡片尚未关联账户");
            return JSONObject.toJSONString(model);
        }
        List<CardAccount> cardAccountList = cardAccountService.query().eq("CUSTOMER_ID", cardInfo.getCustomerId())
                .eq("STATUS", 0).list();
        ArrayList<String> cardAccountTypeList = new ArrayList<>();
        for (CardAccount cardAccount : autoMapper.mapperEntityList(cardAccountList)) {
            cardAccountTypeList.add(cardAccount.getAccountType().getName());
        }

        model.addAttribute("cardAccountTypeList", cardAccountTypeList);
        model.addAttribute("cardAccountList", cardAccountList);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("id", "cardAccountTypeList", "result", "cardAccountList", "accountNo", "amount", "customerId", "name");
        return JSONObject.toJSONString(model, filter, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 获取新增顾客编号
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "getNewNo", method = RequestMethod.POST)
    public String getNewNo(Model model, HttpServletRequest request, HttpServletResponse response) {
        String result = HttpUtil.sendToGet(MSM_PUB_OR_URL + "card/add.do");
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("attributes", "result", "message", "cashPledge", "customerTypeList", "id", "name", "rule", "cardTypeList", "cardRule");
        if (StringUtils.hasText(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result, JSONObject.class);
            return JSONObject.toJSONString(jsonObject, filter);
        } else {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "服务器请求异常");
            return JSONObject.toJSONString(model);
        }
    }

    /**
     * 开卡
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "openCard", method = RequestMethod.POST)
    public String openCard(@RequestBody Map<String, Object> map, Model model, HttpServletRequest request, HttpServletResponse response) {
        SystemAclUser user = (SystemAclUser) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        //先支付订单
        String payType = map.get("payType").toString();
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("customerInfo", JSON.toJSONString(map));
        paramsMap.put("uAccount", user.getLoginName());
        paramsMap.put("uPasswd", user.getPw());
        paramsMap.put("pay_reason", "open_card");
        paramsMap.put("auth_code", map.get("authCode").toString());
        paramsMap.put("listModel", "");
        paramsMap.put("ItemName", "开卡储值");
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
        paramsMap.put("out_trade_no", df.format(LocalDateTime.now()) + UUID.randomUUID().toString().substring(0, 4));
        boolean flag = false;
        String payResult = "";
        if ("1".equals(payType)) {
            //支付宝支付
            payResult = HttpUtil.sendToPostWithParameter(MSM_PUB_OR_URL + "order/alipay.do", paramsMap);
        } else if ("2".equals(payType)) {
            //微信支付
            payResult = HttpUtil.sendToPostWithParameter(MSM_PUB_OR_URL + "order/money.do", paramsMap);
        } else {
            flag = true;
        }
        if (StringUtils.hasText(payResult)) {
            Map<String, String> payMap = JSONObject.parseObject(payResult, Map.class);
            if (payMap.get("is_success").equals("YES") || payMap.get("is_success").equals("支付成功，但订单未打印")) {
                //支付成功
                flag = true;
            }
        } else if (!flag) {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "服务器请求异常");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        }
        String result = HttpUtil.sendToPostWithParameter(MSM_PUB_OR_URL + "card/openAccount.do", paramsMap);
        if (StringUtils.hasText(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result, JSONObject.class);
            return JSONObject.toJSONString(jsonObject, SerializerFeature.IgnoreNonFieldGetter);
        } else {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "服务器请求异常");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        }
    }

}
